package com.city.java.users.service.impl;

import com.city.java.base.utils.PageVO;
import com.city.java.users.mapper.UserMapper;
import com.city.java.users.pojo.entity.Users;
import com.city.java.base.response.JsonResult;
import com.city.java.base.response.StatusCode;
import com.city.java.users.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 用户服务实现类
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    // 账号密码长度校验正则表达式
    private static final Pattern ACCOUNT_PATTERN = Pattern.compile("^.{6,}$");
    private static final Pattern PASSWORD_PATTERN = Pattern.compile("^.{6,}$");

    @Override
    public JsonResult addUser(Users user) {
        log.debug("准备添加用户: {}", user);

        // 参数校验
        if (user == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "用户信息不能为空");
        }

        if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "用户姓名不能为空");
        }

        if (user.getAccount() == null || !ACCOUNT_PATTERN.matcher(user.getAccount()).matches()) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "账号长度必须大于等于6位");
        }

        if (user.getPassword() == null || !PASSWORD_PATTERN.matcher(user.getPassword()).matches()) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "密码长度必须大于等于6位");
        }

        // 检查用户名是否已存在
        if (userMapper.selectByName(user.getUsername()) != null) {
            log.warn("用户名已被占用: {}", user.getUsername());
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }

        // 设置创建时间和更新时间
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());

        try {
            userMapper.insertUser(user);
            log.info("用户添加成功: {}", user.getUsername());
            return JsonResult.ok();
        } catch (Exception e) {
            log.error("添加用户失败: {}", user.getUsername(), e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "添加用户失败");
        }
    }

    @Override
    public JsonResult getUserById(Long userId) {
        log.debug("根据ID查询用户: {}", userId);

        // 参数校验
        if (userId == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "用户ID不能为空");
        }

        try {
            Users user = userMapper.selectById(userId);
            if (user != null) {
                log.info("查询用户成功: ID={}", userId);
                return JsonResult.ok(user);
            } else {
                log.warn("用户不存在: ID={}", userId);
                return new JsonResult(StatusCode.OPERATION_FAILED, "用户不存在");
            }
        } catch (Exception e) {
            log.error("查询用户失败: ID={}", userId, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询用户失败");
        }
    }

    @Override
    public JsonResult getUserByUsername(String username) {
        log.debug("根据用户名查询用户: {}", username);

        // 参数校验
        if (username == null || username.trim().isEmpty()) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "用户名不能为空");
        }

        try {
            Users user = userMapper.selectByName(username);
            if (user != null) {
                log.info("查询用户成功: username={}", username);
                return JsonResult.ok(user);
            } else {
                log.warn("用户不存在: username={}", username);
                return new JsonResult(StatusCode.OPERATION_FAILED, "用户不存在");
            }
        } catch (Exception e) {
            log.error("查询用户失败: username={}", username, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询用户失败");
        }
    }

    @Override
    public PageVO<Users> select(Users users) {
        users.setPageNum(PageVO.build(users.getPageNum(), users.getPageSize()));
        List<Users> list = userMapper.select(users);
        Long totalPage = userMapper.getTotalPage(users);

        PageVO<Users> pageVO = new PageVO<>();
        pageVO.setList(list);
        pageVO.setTotalPage(totalPage);

        log.debug("查询用户列表成功: {}", pageVO);
        return pageVO;
    }

    @Override
    public JsonResult deleteUserById(Long userId) {
        log.debug("根据ID删除用户: {}", userId);

        // 参数校验
        if (userId == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "用户ID不能为空");
        }

        try {
            int result = userMapper.deleteById(userId);
            if (result > 0) {
                log.info("删除用户成功: ID={}", userId);
                return JsonResult.ok();
            } else {
                log.warn("删除用户失败，用户不存在: ID={}", userId);
                return new JsonResult(StatusCode.OPERATION_FAILED, "用户不存在");
            }
        } catch (Exception e) {
            log.error("删除用户失败: ID={}", userId, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "删除用户失败");
        }
    }

    @Override
    public JsonResult deleteUserByUsername(String username) {
        log.debug("根据用户名删除用户: {}", username);

        // 参数校验
        if (username == null || username.trim().isEmpty()) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "用户名不能为空");
        }

        try {
            int result = userMapper.deleteByName(username);
            if (result > 0) {
                log.info("删除用户成功: username={}", username);
                return JsonResult.ok();
            } else {
                log.warn("删除用户失败，用户不存在: username={}", username);
                return new JsonResult(StatusCode.OPERATION_FAILED, "用户不存在");
            }
        } catch (Exception e) {
            log.error("删除用户失败: username={}", username, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "删除用户失败");
        }
    }

    @Override
    public JsonResult updateUser(Users user) {
        log.debug("更新用户信息: {}", user);

        // 参数校验
        if (user == null || user.getUserId() == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "用户ID不能为空");
        }

        try {
            // 检查用户是否存在
            Users existingUser = userMapper.selectById(user.getUserId());
            if (existingUser == null) {
                log.warn("更新用户失败，用户不存在: ID={}", user.getUserId());
                return new JsonResult(StatusCode.OPERATION_FAILED, "用户不存在");
            }

            // 设置更新时间
            user.setUpdatedAt(LocalDateTime.now());

            int result = userMapper.updateById(user);
            if (result > 0) {
                log.info("更新用户成功: ID={}", user.getUserId());
                return JsonResult.ok();
            } else {
                log.warn("更新用户失败: ID={}", user.getUserId());
                return new JsonResult(StatusCode.OPERATION_FAILED, "更新用户失败");
            }
        } catch (Exception e) {
            log.error("更新用户失败: ID={}", user.getUserId(), e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "更新用户失败");
        }
    }
    // 在 UserServiceImpl.java 中添加实现
    @Override
    public JsonResult updateUserPoints(Long userId, Integer points) {
            log.debug("更新用户积分: userId={}, points={}", userId, points);

    // 参数校验
        if (userId == null) {
        return new JsonResult(StatusCode.INVALID_PARAMETER, "用户ID不能为空");
    }

    if (points == null) {
        return new JsonResult(StatusCode.INVALID_PARAMETER, "积分值不能为空");
    }

    try {
        // 查询用户当前积分
        Users user = userMapper.selectById(userId);
        if (user == null) {
            log.warn("更新积分失败，用户不存在: ID={}", userId);
            return new JsonResult(StatusCode.OPERATION_FAILED, "用户不存在");
        }

        // 更新积分（可以是增加或减少）
        Integer currentPoints = user.getPoints() != null ? user.getPoints() : 0;
        user.setPoints(currentPoints + points);

        int result = userMapper.updateById(user);
        if (result > 0) {
            log.info("更新用户积分成功: ID={}, 原积分={}, 变化={}, 现积分={}",
                    userId, currentPoints, points, user.getPoints());
            return JsonResult.ok();
        } else {
            log.warn("更新用户积分失败: ID={}", userId);
            return new JsonResult(StatusCode.OPERATION_FAILED, "更新用户积分失败");
        }
    } catch (Exception e) {
        log.error("更新用户积分失败: ID={}", userId, e);
        return new JsonResult(StatusCode.OPERATION_FAILED, "更新用户积分失败");
    }
}


    @Override
    public String login(Users users) {
        Users queryUser = new Users();
        queryUser.setAccount(users.getAccount());
        queryUser.setPassword(users.getPassword());

        Users auth = userMapper.login(queryUser);
        if(auth != null && auth.getType().equals(Users.UserType.ADMIN)){
            log.debug("用户登录成功: {}", auth);
            return auth.getNickname();
        }else {
            throw new RuntimeException("用户登录失败");
        }
    }
}
